/* cisshPipe.c
 */
#include <u.h>
#include <libc.h>

/* cisshPipe(char* command1[], char* command2[])
 * handles command lines with pipes.
 */
void
cisshPipe(char* command1[], char* command2[])
{
    int pipefd[2];
    int status;
    int left_pid, right_pid;

    if (pipe(pipefd) == -1)
    {
        exits("cissh: cannot open pipe pair");
    }

    /* start command1 with reassigned stdout: command1 > pipefdp[1] */
    if ((left_pid = fork()) == 0)
    {
        close(1);             /* close existing stdout */
        dup(pipefd[1]);       /* set pipe[1] as stdout for child */
        close(pipefd[0]);     /* not using the right side, close */
        execl(command1[0], command1);
        exits("left cissh: side of piping is failed");
    }

    /* start command2 with reassigned stdin: command2 < pipefd[0] */
    if ((right_pid = fork()) == 0)
    {
        close(0);            /* close existing stdin */
        dup(pipefd[0]);      /* set pipe[0] as stdin */
        close(pipefd[1]);    /* not using the left side, close */
        execl(command2[0], command2);
        exits("cissh: right side of piping is failed");
    }

    // parent doesn't need pipes, close both */
    close(pipefd[0]);
    close(pipefd[1]);

    // wait for both children
    wait();
}
